package security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.visural.common.web.client.UserAgent;
import com.visural.common.web.client.WebClient;

/**
 * Servlet Filter implementation class BrowserFilter0
 */
@WebFilter("/BrowserFilter0")
public class BrowserFilter0 implements Filter {

	/**
	 * Default constructor.
	 */
	public BrowserFilter0() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 * 
	 * 
	 *      This method checks the Google Chrome or Mozilla Firefox version
	 *      number and redirects to a website which recommends downloading the
	 *      latest version in case the browser used is outdated
	 * 
	 * 
	 * @param request
	 * @param response
	 * @param chain
	 * 
	 * 
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
	 

		HttpServletRequest request1 = (HttpServletRequest) request;

		HttpServletResponse response1 = (HttpServletResponse) response;
		WebClient client = WebClient.detect(request1);

		if (client.getUserAgent().equals(UserAgent.CHROME)) { //if the browser is Chrome

			int version = Integer.parseInt(client.getFullVersion().substring(0,
					2));

			if (version < 35) {//if the version of Chrome is below 35 redirect to "whatbrowser.org"

				System.out.println("Versiune veche" + version);

				chain.doFilter(request, response);

				response1.sendRedirect("http://whatbrowser.org/");
			} else {//any other case chain the request and response

				chain.doFilter(request, response);

			}
		} else if (client.getUserAgent().equals(UserAgent.FIREFOX)) {//if the browser is Firefox

			int version = Integer.parseInt(client.getFullVersion().substring(0,
					2));

			if (version < 30) {//if the version of Chrome is below 35 redirect to "whatbrowser.org"

				System.out.println("Versiune veche" + version);

				chain.doFilter(request, response);

				response1.sendRedirect("http://whatbrowser.org/");
			} else {

				chain.doFilter(request, response);
			}

		} else {//any other case chain the request and response

			chain.doFilter(request, response);

		}

	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
